package com.lottery.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lottery.server.common.JsonResult;
import com.lottery.server.common.ResultCode;
import com.lottery.server.common.exception.BusinessException;
import com.lottery.server.entity.LotteryRecord;
import com.lottery.server.entity.Prize;
import com.lottery.server.entity.User;
import com.lottery.server.service.LotteryRecordService;
import com.lottery.server.service.PrizeService;
import com.lottery.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;

@RestController
@RequestMapping("/api/lottery/record")
public class LotteryController {
    
    @Autowired
    private PrizeService prizeService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private LotteryRecordService lotteryRecordService;
    
    @PostMapping("/draw")
    public JsonResult<Prize> draw(@RequestParam String phone) {
        // 检查用户是否已抽奖
        QueryWrapper<LotteryRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        if (lotteryRecordService.count(queryWrapper) > 0) {
            throw new BusinessException(ResultCode.DRAW_FAILED, "您已经参与过抽奖");
        }

        // 获取用户信息
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.eq("phone", phone);
        User user = userService.getOne(userQuery);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }

        // 执行抽奖逻辑
        Prize prize = prizeService.drawPrize();
        if (prize == null) {
            throw new BusinessException(ResultCode.PRIZE_STOCK_NOT_ENOUGH);
        }

        // 保存抽奖记录
        LotteryRecord record = new LotteryRecord();
        record.setUserId(user.getId());
        record.setPhone(phone);
        record.setPrizeId(prize.getId());
        record.setPrizeName(prize.getName());
        record.setPrizeValue(prize.getValue());
        lotteryRecordService.save(record);

        return JsonResult.success(prize);
    }

    @GetMapping("/list")
    public JsonResult<Page<LotteryRecord>> getRecords(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String phone) {
        Page<LotteryRecord> page = new Page<>(current, size);
        LambdaQueryWrapper<LotteryRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(phone), LotteryRecord::getPhone, phone);
        wrapper.orderByDesc(LotteryRecord::getCreateTime);
        return JsonResult.success(lotteryRecordService.page(page, wrapper));
    }
} 